<!DOCTYPE html>
<html>
<head>
    <title>数字卡牌对战</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f0f0f0;
        }
        #game-area {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .hand {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin: 20px 0;
            min-height: 100px;
        }
        .card {
            width: 60px;
            height: 80px;
            border: 2px solid #333;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            cursor: pointer;
            background: white;
        }
        .card.x {
            background-color: #ffcccc;
        }
        #discard-pile {
            font-size: 24px;
            margin: 20px 0;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            cursor: pointer;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
        }
        #score {
            margin-top: 20px;
            font-size: 18px;
        }
        #log {
        height: 150px;
        overflow-y: auto;
        border: 1px solid #ddd;
        padding: 10px;
        margin: 10px 0;
        background: #f8f8f8;
    }
    #turn-status {
        color: #d35400;
        font-weight: bold;
        margin: 10px 0;
    }
    </style>
</head>
<body>
    <div id="game-area">
        <div id="turn-status"></div>
        <div id="log"></div>
        <h2>当前弃牌堆：<span id="discard-pile">-</span></h2>
        <div id="ai-hand" class="hand"></div>
        <hr>
        <div id="player-hand" class="hand"></div>
        <div id="actions">
            <button onclick="drawCard()">摸牌</button>
            <button onclick="passTurn()">退出本轮</button>
        </div>
        <div id="status"></div>
        <div id="score">
            玩家得分：<span id="player-score">0</span> 
            AI得分：<span id="ai-score">0</span>
        </div>
    </div>

<script>
let playerPassed = false;
let aiPassed = false;
let lastPlayedCard = '';

// 添加全局变量
let gameLog = [];

// 添加日志功能
function addLog(message) {
    gameLog.push(message);
    if(gameLog.length > 15) gameLog.shift(); // 保留最近15条
    const logDiv = document.getElementById('log');
    logDiv.innerHTML = gameLog.map(msg => `<div>${msg}</div>`).join('');
    logDiv.scrollTop = logDiv.scrollHeight; // 自动滚动到底部
}

let deck = [];
let discardPile = [];
let playerHand = [];
let aiHand = [];
let playerScore = 0;
let aiScore = 0;
let isPlayerTurn = true;

// 初始化牌组
function initializeDeck() {
    deck = [];
    const values = ['1', '2', '3', '4', '5', '6', 'X'];
    values.forEach(value => {
        for(let i=0; i<8; i++) deck.push(value);
    });
    // 洗牌
    deck.sort(() => Math.random() - 0.5);
}

// 发牌
function dealCards() {
    playerHand = deck.splice(0, 6);
    aiHand = deck.splice(0, 6);
    discardPile = [deck.shift()];
}

// 计算可出牌
function getPlayableCards(hand) {
    const topCard = discardPile[discardPile.length-1];
    const nextValues = [];
    
    if(topCard === 'X') {
        nextValues.push('X', '1');
    } else if(topCard === '6') {
        nextValues.push('6', 'X');
    } else {
        const num = parseInt(topCard);
        nextValues.push(topCard, (num+1).toString());
    }
    
    return hand.filter(card => nextValues.includes(card));
}

// AI逻辑
function aiTurn() {
    addLog(`AI的回合开始`);
    lastPlayedCard = discardPile[discardPile.length - 1]; // 获取最新弃牌

    // 如果AI已经退出则直接返回
    if(aiPassed) return;

    // 如果玩家已退出，AI只能选择出牌或退出
    const playable = playerPassed 
        ? getPlayableCards(aiHand) 
        : aiHand.filter(card => canCounter(card, lastPlayedCard));

    // 摸牌条件增加玩家未退出的限制
    const penalty = calculatePenalty(aiHand);
    const shouldDraw = !playerPassed && penalty > 8 && deck.length > 0;

    if(playable.length > 0) {
        playable.sort((a, b) => {
            const valueA = a === 'X' ? 10 : parseInt(a);
            const valueB = b === 'X' ? 10 : parseInt(b);
            return valueA - valueB;
        });
        let playCard = "X"
        if (playable.includes("X") && playable.includes("1")) {
            playCard = "X";
        } else {
            playCard = playable[0];
        }
        addLog(`AI出了 ${playCard}`);
        playAiCard(playCard);
        
        if(!checkEndCondition()) {
            if(!aiPassed && !playerPassed) {
                setTimeout(() => {
                    isPlayerTurn = true;
                    updateGame();
                    addLog(`轮到玩家回合`);
                }, 1000);
            } else {
                setTimeout(aiTurn, 1000);
            }
        }
    } else if(shouldDraw) {
        addLog(`AI选择摸牌`);
        aiHand.push(deck.shift());
        updateGame();
        setTimeout(() => {
            // 摸牌后只有双方都未退出才切换回合
            if(!aiPassed && !playerPassed) {
                isPlayerTurn = true;
                updateGame();
                addLog(`轮到玩家回合`);
            } else {
                setTimeout(aiTurn, 1000); // AI继续行动
            }
        }, 1000);
    } else {
        addLog(`AI选择退出本轮`);
        aiPassed = true;
        
        if(playerPassed) {
            endRound();
        } else {
            // 玩家未退出时移交回合给玩家
            isPlayerTurn = true;
            updateGame();
            addLog(`轮到玩家回合`);
        }
    }
}

// 计算手牌扣分
function calculatePenalty(hand) {
    const unique = [...new Set(hand)];
    return unique.reduce((sum, card) => sum + (card === 'X' ? 10 : parseInt(card)), 0);
}

// 玩家出牌
function playCard(card) {
    if(!isPlayerTurn || playerPassed) return;

    // 检查卡牌是否合法
    const validCards = getPlayableCards(playerHand);
    if(!validCards.includes(card)) {
        addLog(`非法出牌：${card} 不符合规则`);
        return;
    }
    
    addLog(`玩家出了 ${card}`);
    lastPlayedCard = card;
    const index = playerHand.indexOf(card);
    playerHand.splice(index, 1);
    discardPile.push(card);
    updateGame();
    
    if(!checkEndCondition()) {
        // 只有双方都未退出才切换回合
        if(!playerPassed && !aiPassed) {
            isPlayerTurn = false;
            setTimeout(aiTurn, 1000);
        } else {
            setTimeout(() => {
                isPlayerTurn = true; // 保持玩家回合
                updateGame();
            }, 1000);
        }
    }
}

// AI出牌
function playAiCard(card) {
    const index = aiHand.indexOf(card);
    aiHand.splice(index, 1);
    discardPile.push(card);
    lastPlayedCard = card;
    updateGame();
    checkEndCondition();
}

function canCounter(card, previousCard) {
    if (previousCard === 'X') {
        return card === 'X' || card === '1';
    }
    if (previousCard === '6') {
        return card === '6' || card === 'X';
    }
    const num = parseInt(previousCard);
    return card === previousCard || card === (num + 1).toString();
}

function aiDrawCard() {
    if(deck.length > 0) {
        aiHand.push(deck.shift());
        updateGame();
        setTimeout(aiTurn, 1000);
    } else {
        endRound();
    }
}

// 检查结束条件
function checkEndCondition() {
    if(playerHand.length === 0 || aiHand.length === 0) {
        endRound();
        return true;
    }
    return false;
}

// 结束本轮
function endRound() {
    // 重置通行状态
    playerPassed = false;
    aiPassed = false;

    // 计算得分
    playerScore -= calculatePenalty(playerHand);
    aiScore -= calculatePenalty(aiHand);

    const finishCardScore = score => {
        if (score >= -10) return score + 1;
        else {
            return score + 10;
        }
    }
    
    // 出完牌的奖励
    if(playerHand.length === 0) playerScore = finishCardScore(playerScore);
    if(aiHand.length === 0) aiScore = finishCardScore(aiScore);
    
    // 更新显示
    document.getElementById('player-score').textContent = playerScore;
    document.getElementById('ai-score').textContent = aiScore;
    
    // 开始新回合
    initializeDeck();
    dealCards();
    updateGame();
    isPlayerTurn = true;
    document.getElementById('status').textContent = '新回合开始！';
}

// 更新界面
function updateGame() {
    // 更新回合状态显示
    let statusText = `当前回合：`;
    if(playerPassed && aiPassed) {
        statusText += "结算阶段";
    } else if(isPlayerTurn) {
        statusText += "玩家" + (playerPassed ? "（已退出）" : "");
    } else {
        statusText += "AI" + (aiPassed ? "（已退出）" : "");
    }
    document.getElementById('turn-status').textContent = statusText;

    // 玩家手牌
    const playerHandDiv = document.getElementById('player-hand');
    playerHandDiv.innerHTML = playerHand.map(card => 
        `<div class="card ${card === 'X' ? 'x' : ''}" 
              onclick="playCard('${card}')">${card}</div>`
    ).join('');
    
    // AI手牌
    document.getElementById('ai-hand').innerHTML = 
        Array(aiHand.length).fill('<div class="card">?</div>').join('');
    
    // 弃牌堆
    document.getElementById('discard-pile').textContent = 
        discardPile[discardPile.length-1];
    
    // 可用操作
    const playable = getPlayableCards(playerHand);
    document.querySelectorAll('#player-hand .card').forEach((div, i) => {
        div.style.backgroundColor = playable.includes(playerHand[i]) ? '#ccffcc' : 'white';
    });

    // 控制按钮状态
    const drawButton = document.querySelector("button[onclick='drawCard()']");
    drawButton.disabled = playerPassed || !isPlayerTurn || aiPassed;
}

// 玩家摸牌
function drawCard() {
    if(!isPlayerTurn || deck.length === 0) return;
    // 当任一玩家退出后禁止摸牌
    if(!isPlayerTurn || deck.length === 0 || playerPassed || aiPassed) return;
    
    addLog(`玩家摸了一张牌`);
    playerHand.push(deck.shift());
    isPlayerTurn = false;
    updateGame();
    setTimeout(aiTurn, 1000);
}


// 玩家退出
function passTurn() {
    if(!isPlayerTurn || playerPassed) return;
    
    addLog("玩家选择退出本轮");
    playerPassed = true;
    isPlayerTurn = false;
    
    // 检查是否双方都退出
    if(aiPassed) {
        endRound();
    } else {
        isPlayerTurn = false;
        updateGame();
        setTimeout(aiTurn, 1000);
    }
}

// 初始化游戏
initializeDeck();
dealCards();
updateGame();
</script>
</body>
</html>
